package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.UserMapper;
import cn.tedu.weibo.pojo.dto.UserLoginDTO;
import cn.tedu.weibo.pojo.dto.UserRegDTO;
import cn.tedu.weibo.pojo.entity.User;
import cn.tedu.weibo.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    UserMapper mapper;
    @RequestMapping("/reg")
    int reg(@RequestBody UserRegDTO user){
        if(mapper.selectByUsername(user.getUsername())!=null){
            return 2;
        }
        User user1=new User();
        BeanUtils.copyProperties(user,user1);
        mapper.insert(user1);
        return 1;
    }
    @RequestMapping("/login")
    int login(@RequestBody UserLoginDTO user, HttpSession session){
        UserVO userVO=mapper.selectByUsername(user.getUsername());
        if(userVO==null){
            return 2;
        }
        if(userVO.getPassword().equals(user.getPassword())) {
            session.setAttribute("userVO",userVO);
            return 1;
        }else {
            return 3;
        }
    }
    @RequestMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
        return (UserVO) session.getAttribute("userVO");
    }
    @RequestMapping("/exit")
    public void exit(HttpSession session){
        session.removeAttribute("userVO");
    }
}
